package cn.fjc920.siaa.activitys

import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentPagerAdapter
import androidx.viewpager.widget.ViewPager
import cn.fjc920.siaa.R
import cn.fjc920.siaa.activityutils.BaseActivity
import cn.fjc920.siaa.activityutils.Contexts
import cn.fjc920.siaa.fragments.HomeFragment
import cn.fjc920.siaa.fragments.MyFragment
import kotlinx.android.synthetic.main.activity_home_page.*

class HomePageActivity : BaseActivity() {

    private val fragmentList = listOf(HomeFragment(), MyFragment())

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_home_page)

        init()
    }

    private fun init(){

        Contexts.homePageActivity = this

        //fragment缓存
        home_page_viewPager.offscreenPageLimit = fragmentList.size
        home_page_viewPager.adapter = MyAdapter(supportFragmentManager)
        home_page_bottomNavigationView.setOnNavigationItemSelectedListener {
            when(it.itemId){
                R.id.bottom_home -> home_page_viewPager.currentItem = 0
                R.id.bottom_my -> home_page_viewPager.currentItem = 1
            }
            true
        }
        home_page_viewPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener{
            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {

            }

            override fun onPageSelected(position: Int) {
                home_page_bottomNavigationView.menu.getItem(position).isChecked = true
            }

            override fun onPageScrollStateChanged(state: Int) {

            }

        })

    }

    inner class MyAdapter(fm: FragmentManager) : FragmentPagerAdapter(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT){
        override fun getCount(): Int {
            return fragmentList.size
        }

        override fun getItem(position: Int): Fragment {
            return fragmentList[position]
        }

    }

    companion object{
        fun actionStart(context: Context){
            val intent = Intent(context, HomePageActivity::class.java)
            context.startActivity(intent)
        }
    }
}